﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using RED_NET_Core.BLL;
using RED_NET_Core.Entity;
using System.Data.SqlClient;
using System.Text;

namespace RED_NET.ContentPage
{
    public partial class Login_2 : System.Web.UI.Page
    {
        protected int uId;
        private string tvalidator = "";
        private StringBuilder sBuilder = new StringBuilder();
        private readonly String ImageUrl = "~/ContentPage/ValidateImage.aspx?Validator=";
        public String[] Picture, adURLs;
        public string testString = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USER"] != null)//登录好了
            {
                //转到主页
                Response.Redirect("~/ContentPage/Login.aspx");
            }
            else//未登录
            {
                if (!IsPostBack)
                {
                    tvalidator = GetValidatorString(4);
                    ViewState["validatorString"] = tvalidator;
                }
                else
                {
                    tvalidator = ViewState["validatorString"].ToString();
                }
                validatorImage.ImageUrl = ImageUrl + tvalidator;
            }
        }

        //创建随机数
        private int GetRandomInt(int min, int max)
        {
            Random random = new Random(Guid.NewGuid().GetHashCode());
            return random.Next(min, max);
        }
        //获取随机产生的四个字符
        private string GetValidatorString(int lenth)
        {
            InitStringBuilder();
            int x;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < lenth; i++)
            {
                x = GetRandomInt(0, sBuilder.Length - 1);
                sb.Append(sBuilder[x].ToString());
                sBuilder.Remove(x, 1);
            }
            return sb.ToString();
        }
        //添加所有用于验证的字符
        private void InitStringBuilder()
        {
            int i;
            for (i = 0; i < 10; i++)
                sBuilder.Append(i.ToString());
            for (i = 0; i < 26; i++)
                sBuilder.Append((char)('a' + i));
            for (i = 0; i < 26; i++)
                sBuilder.Append((char)('A' + i));
        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            LoginBLL nlogin = new LoginBLL();
            //先判断验证码是否错误，如果错误就不用访问数据库了
            tvalidator = ViewState["validatorString"].ToString().ToLower();
            if (validatorString.Text.Trim().ToLower() != tvalidator)
            {
                Response.Write("<script>alert('验证码错误！');</script>");
                tvalidator = GetValidatorString(4);
                ViewState["validatorString"] = tvalidator;
                validatorImage.ImageUrl = ImageUrl + tvalidator;
                return;
            }
            else
            {
                try
                {
                    uId = nlogin.GetUserId(userName.Text.Trim(), password.Text.Trim());
                }
                catch (Exception ex)
                {
                    //记录错误信息
                    //Users user = (Users)Session["USER"]; （无用户）
                    //int User_Id = user.UserId;
                    DateTime time = DateTime.Now;
                    ErrorInfo_BLL.AddErrorInfo(0, ex.Message, time);//（0代表无用户）
                    //转到错误页面
                    Response.Redirect("~/ContentPage/Error/PageError.aspx");
                }
                Session["USER_ID"] = uId;
                if (Int32.Parse(Session["USER_ID"].ToString()) == -1)
                {
                    Response.Write("<script>alert('帐号或密码错误！');</script>");
                    Session["USER_ID"] = null;
                }
                else
                {
                    Users user = nlogin.GetMessageOfUser(uId);
                    Session["USER"] = (object)user;
                    Response.Write("<script>alert('登录成功！');location.href='Login.aspx';</script>");
                }
            }
        }

        protected void validatorImage_Click(object sender, ImageClickEventArgs e)
        {
            tvalidator = GetValidatorString(4);
            ViewState["validatorString"] = tvalidator;
            validatorImage.ImageUrl = ImageUrl + tvalidator;
        }
    }
}
